﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using System.Text;


public partial class User_Shares_ExcelOutputMultiple : System.Web.UI.Page
{

    private int _AdvisorDelay;
    public int AdvisorDelay
    {
        get { return _AdvisorDelay; }
        set
        {
            _AdvisorDelay = value;
        }
    }

    private int _FourthFactorDelay;
    public int FourthFactorDelay
    {
        get { return _FourthFactorDelay; }
        set
        {
            _FourthFactorDelay = value;
        }
    }
    

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ContractIds"] != null)
        {
            var datasource = ExcelOutput.ExcelOutputMaker((List<Guid>)Session["ContractIds"]);
            Session["ContractIds"] = null;
            GridView gridVillage, gridContractInfo, gridProjectStatus;

            GridViewExcelOutput.DataSource = datasource;
            List<ExcelType> datasourceRow;
            GridViewExcelOutput.DataBind();
            List<int> delays = new List<int>();
            for (int i = 0; i < GridViewExcelOutput.Rows.Count; i++)
            {
                AdvisorDelay = FourthFactorDelay = 0;
                gridVillage = GridViewExcelOutput.Rows[i].FindControl("GridViewVillage") as GridView;
                gridContractInfo = GridViewExcelOutput.Rows[i].FindControl("GridViewContractInfo") as GridView;
                gridProjectStatus = GridViewExcelOutput.Rows[i].FindControl("GridViewProjectStatus") as GridView;
                

                Guid contractId;
                if (GridViewExcelOutput.DataKeys != null)
                {
                    contractId = new Guid(GridViewExcelOutput.DataKeys[i].Value.ToString());
                    datasourceRow = ExcelOutput.ExcelOutputRow(contractId);


                    if (gridVillage != null)
                    {
                        gridVillage.DataSource = datasourceRow;
                        gridVillage.DataBind();
                    }

                    if (gridContractInfo != null)
                    {
                        gridContractInfo.DataSource = datasourceRow;
                        gridContractInfo.DataBind();
                    }

                    if (gridProjectStatus != null)
                    {
                        int count = CommonCalculations.StepsCount(contractId);
                        ExcelType temp = new ExcelType();
                        temp.Tasks = Business.CommonCalculations.EmptyListOfSteps(contractId);
                        datasourceRow[0].Tasks = datasourceRow[0].Tasks.OrderBy(task => task.StepPriority).ToList();
                        foreach ( var task in temp.Tasks )
                        {
                            Business.CompareSteps compareSteps = new CompareSteps();
                            compareSteps.IsAdvisor = CommonCalculations.ContractType( contractId );
                            if(datasourceRow[0].Tasks.BinarySearch( task , compareSteps )>0)
                            {
                                continue;
                            }
                            else
                            {
                                datasourceRow[0].Tasks.Add( task );
                            }
                        }

                        datasourceRow[0].Tasks = datasourceRow[0].Tasks.OrderBy(task => task.StepPriority).ThenBy(task => task.DateDone).ToList();
                        
                        
                        
                        //this part removes redundant items from list.

                        int index = 0;
                        if (CommonCalculations.ContractType(contractId))
                        {
                            while (index < datasourceRow[0].Tasks.Count-1)
                            {
                                if (datasourceRow[0].Tasks[index].AdvisorStepId
                                     == datasourceRow[0].Tasks[index + 1].AdvisorStepId)
                                {
                                    switch (datasourceRow[0].Tasks[index].InputGuy)
                                    {
                                        case InputGuyType.InputGuy.Advisor:
                                            AdvisorDelay += datasourceRow[0].Tasks[index].Latency;
                                            break;
                                        case InputGuyType.InputGuy.FourthFactor:
                                            FourthFactorDelay += datasourceRow[0].Tasks[index].Latency;
                                            break;
                                    }
                                    datasourceRow[0].Tasks.RemoveAt(index);
                                }
                                else
                                {
                                    index++;
                                }
                            }
                        }
                        else
                        {
                            while ( index < datasourceRow[ 0 ].Tasks.Count-1 )
                            {
                                if ( datasourceRow[ 0 ].Tasks[ index ].SurveyorStepId
                                     == datasourceRow[ 0 ].Tasks[ index + 1 ].SurveyorStepId )
                                {
                                    switch ( datasourceRow[ 0 ].Tasks[ index ].InputGuy )
                                    {
                                        case InputGuyType.InputGuy.Advisor:
                                            AdvisorDelay += datasourceRow[ 0 ].Tasks[ index ].Latency;
                                            break;
                                        case InputGuyType.InputGuy.FourthFactor:
                                            FourthFactorDelay += datasourceRow[ 0 ].Tasks[ index ].Latency;
                                            break;
                                    }
                                    datasourceRow[ 0 ].Tasks.RemoveAt( index );
                                }
                                else
                                {
                                    index++;
                                }
                            }
                        }


                        delays = ColumnsMaker(count, datasourceRow, gridProjectStatus);
                        gridProjectStatus.DataSource = datasourceRow;
                        gridProjectStatus.Width = count * 150;
                        gridProjectStatus.HeaderStyle.Width = 150;
                        //firstRow.Height = 120;
                        gridProjectStatus.DataBind();
                        AdvisorDelay += delays[0];
                        FourthFactorDelay += delays[1];
                        Label fourthfactorLabel = GridViewExcelOutput.Rows[i].FindControl("LabelFourthFactor") as Label;
                        Label advisorLabel = GridViewExcelOutput.Rows[i].FindControl("LabelAdvisor") as Label;
                        if (fourthfactorLabel != null)
                            fourthfactorLabel.Text = string.Format("میزان دیرکرد عامل جهار:{0} روز", FourthFactorDelay);
                        if (advisorLabel != null)
                            advisorLabel.Text = string.Format("میزان دیرکرد مشاور / نقشه بردار:{0} روز", AdvisorDelay);
                        gridProjectStatus.HeaderRow.Attributes["id"] = "equalize";
                    }
                }
            }
        }
    }
    

    private static List<int> ColumnsMaker(int upperLimit, List<ExcelType> datasourceRow, GridView gridProjectStatus)
    {
        //return value of method to show in Grid, where it shows delay for advisor and surveyour.
        List<int> outputDelay = new List<int>();
        int startIndex;
        int endIndex;
        int advisorDelay = 0, fourthFactorDelay = 0;

        for (int i = 0; i < upperLimit; i++)
        {
            TemplateField templateField = new TemplateField();
            var item = datasourceRow[0].Tasks[i];

                switch (item.InputGuy)
                {
                    case InputGuyType.InputGuy.Advisor:
                        templateField.ItemTemplate = new TemplateHandler(item.DateDoneFarsi, "", "", "", item.Latency.ToString(), true);
                        advisorDelay += item.Latency;
                        break;
                    case InputGuyType.InputGuy.BonyadeShahrestan:
                        templateField.ItemTemplate = new TemplateHandler("", "", item.DateDoneFarsi, "", item.Latency.ToString(), true);
                        break;
                    case InputGuyType.InputGuy.Employer:
                        templateField.ItemTemplate = new TemplateHandler("", item.DateDoneFarsi, "", "", item.Latency.ToString(), true);
                        break;
                    case InputGuyType.InputGuy.FourthFactor:
                        templateField.ItemTemplate = new TemplateHandler("", "", "", item.DateDoneFarsi, item.Latency.ToString(), true);
                        fourthFactorDelay += item.Latency;
                        break;
                    default:
                        templateField.ItemTemplate = new TemplateHandler(item.DateDoneFarsi, "--", "--", "--", item.Latency.ToString(), true);
                        break;
                }
            

            templateField.HeaderText = item.StepName;
            templateField.HeaderStyle.Wrap = true;
            templateField.HeaderStyle.Font.Bold = true;
            gridProjectStatus.Columns.Add(templateField);
            outputDelay.Add(advisorDelay);
            outputDelay.Add(fourthFactorDelay);
        }
        return outputDelay;
    }
    
    protected void ExportToExcel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = System.Text.Encoding.Unicode;
            Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            this.EnableViewState = false;
            StringWriter sr = new StringWriter();
            HtmlTextWriter hr = new HtmlTextWriter(sr);
            Panel1.RenderControl(hr);
            Response.Write(sr.ToString());
            sr.Dispose();
            hr.Dispose();
            Response.End();        

        }
        catch (Exception ex)
        {
        }
    }

   public override void VerifyRenderingInServerForm(Control control)
    {
    }


    protected void ExportToWord_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
            Response.ContentType = "application/vnd.word";
            Response.ContentEncoding = System.Text.Encoding.Unicode;

            Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            this.EnableViewState = false;
            StringWriter sr = new StringWriter();
            System.Web.UI.HtmlTextWriter hr = new HtmlTextWriter(sr);
            GridViewExcelOutput.RenderControl(hr);
            Response.Write(sr.ToString());
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            sr.Dispose();
            hr.Dispose();
            Response.End();
        }
        catch (Exception ex)
        {
        }
    }
  

    //protected void btnPrint_Click(object sender, EventArgs e)
    //{
    //    StringWriter sw = new StringWriter();

    //    HtmlTextWriter hw = new HtmlTextWriter(sw);

    //    GridViewExcelOutput.RenderControl(hw);

    //    string gridHTML = sw.ToString().Replace("\"", "'")

    //        .Replace(System.Environment.NewLine, "");

    //    StringBuilder sb = new StringBuilder();

    //    sb.Append("<script type = 'text/javascript'>");

    //    sb.Append("window.onload = new function(){");

    //    sb.Append("var printWin = window.open('', '', 'left=0");

    //    sb.Append(",top=0,width=1000,height=600,status=0');");

    //    sb.Append("printWin.document.write(\"");

    //    sb.Append(gridHTML);

    //    sb.Append("\");");

    //    sb.Append("printWin.document.close();");

    //    sb.Append("printWin.focus();");

    //    sb.Append("printWin.print();");

    //    sb.Append("printWin.close();};");

    //    sb.Append("</script>");

    //    ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());



    //}
    protected void GridViewExcelOutput_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //        gridVillage = GridViewExcelOutput.Rows[i].FindControl("GridViewVillage") as GridView;
        //gridContractInfo = GridViewExcelOutput.Rows[i].FindControl("GridViewContractInfo") as GridView;
        //gridProjectStatus = GridViewExcelOutput.Rows[i].FindControl("GridViewProjectStatus") as GridView;
        if ( e.Row.RowIndex > 0 )
        {
            ( ( GridView ) e.Row.FindControl( "GridViewVillage" ) ).ShowHeader = false;
            ( ( GridView ) e.Row.FindControl( "GridViewContractInfo" ) ).ShowHeader = false;
            ( ( GridView ) e.Row.FindControl( "GridViewProjectStatus" ) ).ShowHeader = false;
            ((Panel)e.Row.FindControl("PanelAdvisor")).Visible = false;
            (( Panel ) e.Row.FindControl("PanelTiming")).Visible = false;
        }
    }
}